<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>微框架2</title>
  </head>

  <body>
    <!-- 4个Dom元素挂载着2个【响应式数据】 -->
    <h3 id="hMyname">{name}</h3>
    <p id="pMyname">{name}</p>

    <h3 id="hMyage">{age}</h3>
    <p id="pMyage">{age}</p>

    <script>
      function defineReactive(data, key, doms = []) {
        Object.defineProperty(data, key, {
          // 读取data.age
          get() {
            console.log("get", key);
            return data[`x_${key}`];
          },

          // 设置data.age = 19
          set(newValue) {
            console.log("set", key, newValue);
            data[`x_${key}`] = newValue;

            /* 通知age的观察者来响应 */
            // hMyage.innerText = newValue;
            // pMyage.innerText = newValue;
            doms.forEach((dom) => (dom.innerText = newValue));
          },
        });
      }
    </script>

    <script>
      const data = {
        // name: "黑哥",
        // age: 18,

        /* 数据的真正载体 */
        x_name: "黑哥",
        x_age: 18,
      };

      defineReactive(data, "age", [hMyage, pMyage]);
      defineReactive(data, "name", [hMyname, pMyname]);

      setInterval(() => {
        data.name = Date.now();
        data.age = data.age + 1;
      }, 1000);
    </script>
  </body>
</html>
